/* $RCSFile: AddModule.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Modules/AddModule.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:56  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Helpers;
using AddonNice.Security;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;


namespace AddonNice.PageModules.Modules
{
	/// <summary>
	/// It allows administrators to give permission to selected roles to add modules to pages
	/// </summary>
	public partial class AddModule : PortalModuleControl
	{
		#region General Implementation
		/// <summary>
		/// Gets the GUID for this module.
		/// </summary>
		/// <value></value>
		public override Guid GuidID
		{
			get
			{
				return new Guid(StStr.AddModuleGuid);
			}
		}

		/// <summary>
		/// Marks This Module To be an Admin Module
		/// </summary>
		public override bool AdminModule
		{
			get
			{
				return true;
			}
		}

		/// <summary>
        /// Ctor
		/// </summary>
        public AddModule()
		{   
            ValidationGroup =   "Main";
		}
		#endregion

		#region Page Load

		private void Page_Load(object sender, System.EventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule Page_Load BEG IsPostBack: {0}.",IsPostBack),ModuleTraceSwitch.Sw.Info);
            AddAjaxSetting(moduleType,moduleType);
            AddAjaxSetting(moduleType,HlpPnl);
            AddAjaxSetting(moduleType,TbNewModuleTitle);
            AddAjaxSetting(moduleType,moduleError);
			// If first visit to the page, update all entries
			if ( !IsPostBack ) 
			{
                string msg                          =   LocalizeHelper.Localize("MODULE_CONFIRMADD", "Confirm adding Module ?");
                string strtitle                     =   LocalizeHelper.Localize("MODULE_ADDTOPAGE_TITLE", "Add Module to Page");
                ADNPage.setClientConfirmAttributes(AddModuleBtn,msg,strtitle);
				BindData();
				SetHelpPath();
			}
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine("[V]AddModule Page_Load END.",ModuleTraceSwitch.Sw.Info);
		}
		#endregion
	
		#region Methods

        private void BindData() 
		{
			// Populate the "Add Module" Data
            moduleType.SelectFirst  =   true;
            moduleType.DataBind();
            if ( !string.IsNullOrEmpty(moduleType.Text) )
                SetModuleName(moduleType.Text);
		}

		/// <summary>
		/// Gets the folder help path.
		/// </summary>
		private string GetHelpPath(string desktopSrc)
		{
			string helpPath = desktopSrc.Replace(".","_").ToString();
			return "ADNCRM/" + helpPath;
		}

		/// <summary>
		/// Adapt Title to module name
		/// </summary>
		private void SetModuleName(string nm)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule SetModuleName nm: {0}.",nm),ModuleTraceSwitch.Sw.Info);
		    TbNewModuleTitle.Text = string.Format("{0}{1}",nm,1);
		}

		/// <summary>
		/// Sets the help path. This method checks to see whether the currently selected module has a
		/// help file associated with it. If it does then it shows the help icon. If it doesn't then it
		/// hides it.
		/// </summary>
        private void SetHelpPath()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule SetHelpPath BEG moduleType.SelectedValue: '{0}'.",( moduleType.SelectedValue == null ) ? string.Empty : moduleType.SelectedValue),ModuleTraceSwitch.Sw.Info);
            if ( !string.IsNullOrEmpty(moduleType.SelectedValue) )
            {
                SetHelpPath(moduleType.SelectedValue);
            }
        }

        private void SetHelpPath(string selectedModule)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule SetHelpPath BEG selectedModule: '{0}'.",selectedModule),ModuleTraceSwitch.Sw.Info);
            bool exists                 =   false;
            int moduleDefID	            =   Convert.ToInt32(selectedModule);
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
		        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule SetHelpPath moduleDefID: '{0}'.",moduleDefID),ModuleTraceSwitch.Sw.Info);
            string folderName           =   string.Empty;
            SqlDataReader dr            =   null;
            try
            {
                dr = new ModulesDB().GetModuleDefinitionsByDefId(moduleDefID);
                while (dr.Read())
                {
                    folderName          =  (string)dr[StStr.DBDesktopSrc];
                }
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError)
		            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule SetHelpPath ex: {0}.",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if (dr != null)
                    dr.Close();
            }
	        string aux                  =   folderName.Replace(".","_").ToString();
			int fileNameStart           =   aux.LastIndexOf("/");
			string fileName             =   aux.Substring(fileNameStart+1);
            string strHelpPath          =   Config.HelpPath.TrimStart(new char[]{'~','/'}); // remove '~/'
            string hlpPath              =   string.Format("{0}/{1}/AddonNice/{2}/{3}.xml",
                                                    new object[]{Path2.ApplicationRoot, strHelpPath,aux, fileName});
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
		        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule SetHelpPath hlpPath: '{0}'.",hlpPath),ModuleTraceSwitch.Sw.Info);
            if (System.IO.File.Exists(Server.MapPath(hlpPath)))
            {
                exists                  =   true;
                ImgBtnHelp.Visible      =   true;
                ImgBtnHelp.PopUp        =   true;
			    string hlpUrl           =   string.Format("{0}/{1}/HelpViewer.aspx?loc=AddonNice/{2}&src={3}",
                                                new object[]{Path2.ApplicationRoot,strHelpPath,aux,fileName}); 
                ImgBtnHelp.HRef         =   hlpUrl;
                ImgBtnHelp.PopUpOptions =   "toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width=800,height=600,screenX=15,screenY=15,top=15,left=15";
            }
            else
            {
                ImgBtnHelp.Visible = false;
            }
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule SetHelpPath exists: {0}.",exists),ModuleTraceSwitch.Sw.Info);
		}
         
		#endregion

		#region Events

        /// <summary>
		/// Each time the module selection is changed it checks to see if that particular module has a help file.
		/// </summary>
        void moduleType_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule moduleType_SelectedIndexChanged BEG e.Text: {0}.",e.Text),ModuleTraceSwitch.Sw.Info);
			SetHelpPath(e.Value);		
			SetModuleName(e.Text);
		}

		/// <summary>
		/// Add a new module in the current Page
		/// </summary>
		void AddModuleBtn_Click(object sender, ImageClickEventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule AddModule_Click SelectedValue is null: {0}.",moduleType.SelectedValue == null),ModuleTraceSwitch.Sw.Info);
			// All new modules go to the end of the contentpane
			string selectedModule			=   moduleType.SelectedValue;

            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule AddModule_Click SelectedModule: {0}.",selectedModule),ModuleTraceSwitch.Sw.Info);
			
			// Clear error message in case there was a previous error.
			moduleError.Text                =   string.Empty;

			// This allows the user to pick what type of people can view the module being added.
			// If Authorised Roles is selected from the dropdown then every role that has view permission for the
			// Add Role module will be added to the view permissions of the module being added.
		    ModuleItem m				    =   new ModuleItem();
			try
			{
			    int moduleDefID				=   Convert.ToInt32(selectedModule);
				m.Title						=   TbNewModuleTitle.Text.Trim();
				m.ModuleDefID				=   moduleDefID;
				m.Order						=   999;
				// save to database
                if ( ModuleTraceSwitch.Sw.TraceVerbose)
			        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule AddModule_Click save to database newModuleTitle: {0}, moduleDefID: {1}.",
                        m.Title,moduleDefID),ModuleTraceSwitch.Sw.Info);
                m.ID						=   new ModulesDB().AddModule(PageID, 
                                                                            m.Order, 
                                                                            0,
                                                                            paneLocation.SelectedValue.ToString(), 
                                                                            m.Title, 
                                                                            m.ModuleDefID, 
                                                                            0, 
                                                                            DBAllUser2, DBAllUser2, DBAllUser2, DBAllUser2, Config.InternalAdminRole, Config.InternalAdminRole, Config.InternalAdminRole, 
                                                                            false, 
                                                                            false);
			}
			catch(Exception ex)
			{
                if ( ModuleTraceSwitch.Sw.TraceError )
				    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddModule AddModule_Click ex :{0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
			}
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule AddModule_Click created ModuleID: {0}",m.ID),ModuleTraceSwitch.Sw.Info);
            string virtualPath              =   HttpUrlBuilder.BuildUrl(PageID);
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule AddModule_Click END virtualPath: {0}",virtualPath),ModuleTraceSwitch.Sw.Info);
            ADNPage.Redirect(virtualPath,true);
		}

        #endregion

		#region Std Overrides

        override protected void OnInit(EventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddModule OnInit BEG IsPostBack: {0}.",IsPostBack),ModuleTraceSwitch.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
            if ( ModuleTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine("[V]AddModule OnInit END.",ModuleTraceSwitch.Sw.Info);
		}

		private void InitializeComponent()
		{
			moduleType.SelectedIndexChanged     +=  new RadComboBoxSelectedIndexChangedEventHandler(moduleType_SelectedIndexChanged);
            moduleType.AutoPostBack             =   true;
			AddModuleBtn.Click                  +=  new ImageClickEventHandler(AddModuleBtn_Click);
			Load                                +=  new EventHandler(Page_Load);
		}

        #endregion
	}
}
